package com.lrkj.back.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lrkj.back.entity.ZsPackageImformation;
import com.lrkj.back.entity.ZsWupinShiyong;
import com.lrkj.back.vo.AePackageVO;
import com.lrkj.back.service.TbDepartmentService;
import com.lrkj.back.service.TbSeqService;
import com.lrkj.back.service.ZsWupinShiyongService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lrkj.back.Const;
import com.lrkj.back.entity.TbDepartment;
import com.lrkj.back.entity.TbPackageMuban;
import com.lrkj.back.service.TbPackageMubanService;
import com.lrkj.back.service.ZsPackageImformationService;
import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
@Controller
@RequestMapping("/shoushubaoshiyong")
public class ZsWupinShiyongController extends BaseController{
	@Autowired
	private ZsWupinShiyongService wupinshiyongService;
	@Autowired
	private TbSeqService seqservice;
	@Autowired
	private ZsPackageImformationService packageService;
	@Autowired
	private TbDepartmentService departService;
	@Autowired
	private TbPackageMubanService packageMubanService;
	@Autowired
	private ZsPackageImformationService imformationService;
	@Autowired
	private TbSeqService seqService;

	//临床科室--包使用记录
	@RequestMapping("/shoushubaoRecord.do")
	public ModelAndView packageingList(String searchTxt,String quzhi,String searchLeixin,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException, ParseException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> pagemap =new HashMap<>();
		Map<String,Object> map =new HashMap<>();
		String st = request.getParameter("startTime");
        String et = request.getParameter("endTime");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<String> varList = new ArrayList<>();
        List<String> intList = new ArrayList<>();
        Date startTime = null;
        Date endTime = null;
		//多字段模糊查询
        if (StringUtils.isNotBlank(searchTxt)) {
			map.put("tiaojian", searchTxt);
		}
        List<TbDepartment> department = departService.findDepartment(map);
        List<ZsWupinShiyong> wupinShiyongs = wupinshiyongService.findAllNoPage(map);
//        List<ZsPackageImformation> packageImformations = packageService.findAll(map);
        if (!department.isEmpty()) {
        	for (TbDepartment tbDepartment : department) {
				if (!varList.contains(tbDepartment.getDepartmentId())) {
					varList.add(tbDepartment.getDepartmentId().toString());
				}
			}
        	pagemap.put("shiyongkeshiArr", varList);
        }
        if (!wupinShiyongs.isEmpty()) {
        	for (ZsWupinShiyong shiyong : wupinShiyongs) {
				if (!intList.contains(shiyong.getPatientId())) {
					intList.add(shiyong.getPatientId());
				}
			}
        	pagemap.put("patientIdArr", intList);
        }
//        if (!packageImformations.isEmpty()) {
//			for (ZsPackageImformation zsPackageImformation : packageImformations) {
//				if (!varList.contains(zsPackageImformation.getPackageTiaoma())) {
//					varList.add(zsPackageImformation.getPackageTiaoma());
//				}
//			}
//			pagemap.put("packageArr", varList);
//		}
//        if (department.isEmpty()&&wupinShiyongs.isEmpty()&&packageImformations.isEmpty()) {
//        	varList.add("0");
//        	intList.add("0");
//        	pagemap.put("shiyongkeshiArr",varList);
//		}
        if (StringUtils.isNotBlank(st)) {
        	startTime = sdf.parse(st);
        	pagemap.put("startTime",startTime);
		}
        if (StringUtils.isNotBlank(et)) {
        	endTime = sdf.parse(et);
        	pagemap.put("endTime", endTime);
		}
        pagemap.put("pageNo", pageNo);
        pagemap.put("pageSize", Const.PAGE_SIZE);
		PageInfo<ZsWupinShiyong> page = wupinshiyongService.findAllbaoRecord(pagemap);
		request.setAttribute("fafangList", page.getList());
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		request.setAttribute("startTime",startTime);
		request.setAttribute("endTime",endTime);
		request.setAttribute("tiaojian", searchTxt);
		return new ModelAndView("/linchuang/baoshiyongjilu/bao_record");
	}
	//点添加和修改按纽用到的方法
	@RequestMapping("/shoushubaoEdit.do")
	public ModelAndView packageingEdit(String id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		ZsWupinShiyong wupinshiyong = (id == null) ? new ZsWupinShiyong() : wupinshiyongService.selectByPrimaryKey(id);
		request.setAttribute("dabao", wupinshiyong);
		return new ModelAndView("/linchuang/baoshiyongjilu/bao_edit");
	}
	//修改和保存的方法
	/**
	 * @param request
	 * @param response
	 * @throws ParseException 
	 */
	@RequestMapping("/shoushubaoSave.do")
	@ResponseBody
	public Map<Object, Object> packageingSave(HttpServletRequest request,HttpServletResponse response) throws BusinessException,ParseException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		Date date = new Date();
		SimpleDateFormat sdf1= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String wupinbaoTiaoma = request.getParameter("wupinbaoTiaoma");
		String wupinbaoMingcheng = request.getParameter("wupinbaoMingcheng");
		String shiyongkeshi = request.getParameter("shiyongkeshi");
		String patient = request.getParameter("patientId");
		String patientHospital = request.getParameter("patientHospitalNo");
		String shoushuTemp = request.getParameter("shoushuTemplate");
		String shiyong = request.getParameter("shiyongTime");
		String beizhu = request.getParameter("beizhu");
		Date shiyongTime = sdf1.parse(shiyong);
//		Integer patientId = Integer.valueOf(patient);
//		Integer patientHospitalNo = Integer.valueOf(patientHospital);
//		Integer shoushuTemplate = Integer.valueOf(shoushuTemp);
		ZsPackageImformation packageImformation = new ZsPackageImformation();
		try {
            ZsWupinShiyong wupinshiyong = new ZsWupinShiyong();
			wupinshiyong.setRecordTime(date);
			if(StringUtils.isNotBlank(wupinshiyong.getShiyongLiushui())){
				/*packageImformation.setShiyongkeshi(shiyongkeshi);
				packageImformation.setShiyongLiushui(shiyongLiushui);
				packageImformation.setPatientId(patientId);
				packageImformation.setPatientHospitalNo(patientHospitalNo);
				packageImformation.setShiyongTime(shiyongTime);
				packageImformation.setShoushuTemplate(shoushuTemplate.toString());
				packageImformation.setPackageTiaoma(wupinbaoTiaoma);
				packageService.updateByPrimaryKey(packageImformation);*/
				//修改
				wupinshiyong.setBeizhu(beizhu);
				wupinshiyong.setPatientHospitalNo(patientHospital);
				wupinshiyong.setPatientId(patient);
				wupinshiyong.setShiyongkeshi(shiyongkeshi);
				wupinshiyong.setShiyongTime(shiyongTime);
				wupinshiyong.setShoushuTemplate(shoushuTemp);
				wupinshiyong.setWupinbaoMingcheng(wupinbaoMingcheng);
				wupinshiyong.setWupinbaoTiaoma(wupinbaoTiaoma);
				wupinshiyongService.updateByPrimaryKey(wupinshiyong);
			}else{
				//添加
				packageImformation.setShiyongkeshi(shiyongkeshi);
				packageImformation.setPatientId(patient);
				packageImformation.setPatientHospitalNo(patientHospital);
				packageImformation.setShiyongTime(shiyongTime);
				packageImformation.setShoushuTemplate(shoushuTemp);
				packageImformation.setPackageTiaoma(wupinbaoTiaoma);
				ZsPackageImformation packageInfo = packageService.selectByPrimaryKey(wupinbaoTiaoma);
				TbPackageMuban packageMuban = packageMubanService.selectByPrimaryKey(packageInfo.getPackageTiaoma());
				if (packageMuban!=null) {
					if (packageMuban.getPackageDepartid()!=null) {
						packageImformation.setPackageLiuchengZhuangtai(0);
					}else {
						packageImformation.setPackageLiuchengZhuangtai(7);
					}
				}
				packageService.updateByPrimaryKey(packageImformation);
				SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMdd");
				String shiyongliushui = sdf.format(date)+seqservice.seqVal("wupinsyno");
				wupinshiyong.setBeizhu(beizhu);
				wupinshiyong.setPatientHospitalNo(patientHospital);
				wupinshiyong.setPatientId(patient);
				wupinshiyong.setShiyongLiushui(shiyongliushui);
				wupinshiyong.setShiyongkeshi(shiyongkeshi);
				wupinshiyong.setShiyongTime(shiyongTime);
				wupinshiyong.setShoushuTemplate(shoushuTemp);
				wupinshiyong.setWupinbaoMingcheng(wupinbaoMingcheng);
				wupinshiyong.setWupinbaoTiaoma(wupinbaoTiaoma);
				wupinshiyongService.insert(wupinshiyong);
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping("/shoushubaoDel.do")
	@ResponseBody
	public Map packageingDel(HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for(String tid : arraId){
				wupinshiyongService.deleteByPrimaryKey(tid);
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	//右边显示详细信息的方法,
	@RequestMapping("/shoushubaoshiyongDetailList.do")
	@ResponseBody
	public Map<Object, Object> shoushubaoApplyDetailList(String id,HttpServletRequest request, HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			Map<String,Object> map =new HashMap<String,Object>();
			if(StringUtils.isNotBlank(id)){
				map.put("shiyongLiushui", id);
			}
			ZsWupinShiyong shoushubao =wupinshiyongService.selectByPrimaryKey(id); ;
			rtnMap.put("mxList", shoushubao);
			rtnMap.put("status", "true");
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
		
	//手术室使用包的记录(手麻系统传递过来的数据)
    @RequestMapping("shoushushiShiyong.do")
	@ResponseBody
    public Map<Object, Object> shoushushiShiyong(String appid, String packageList)throws BusinessException, IOException{
    	Map<Object, Object> rtnMap = new HashMap<>();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyMMHH");
    	Date date = new Date();
    	try {
    		JSONArray jArray=JSON.parseArray(packageList);
          	String zhiString=jArray.toString();
        	List<AePackageVO> packageVOs = new ArrayList<>();
        	List<ZsWupinShiyong> shiyongs = new ArrayList<>();
        	List<ZsPackageImformation> imformations = new ArrayList<>();
        	packageVOs = JSONObject.parseArray(zhiString, AePackageVO.class); 
        	Long [] seqVal = seqService.seqValBatch("shiyongliushui",packageVOs.size());
        	ZsWupinShiyong wupinShiyong = null;
        	ZsPackageImformation packageImformation = null;
        	int i = 0;
        	for (AePackageVO aePackageVO : packageVOs) {
        		wupinShiyong = new ZsWupinShiyong();
        		packageImformation = new ZsPackageImformation();
        		wupinShiyong.setShiyongLiushui(sdf.format(date)+seqVal[i]);
        		wupinShiyong.setWupinbaoTiaoma(aePackageVO.getWupinbaoTiaoma());
        		wupinShiyong.setShiyongkeshi("15");
        		wupinShiyong.setPatientId(aePackageVO.getPatientId());
        		wupinShiyong.setPatientHospitalNo(aePackageVO.getHosId());
        		wupinShiyong.setShoushuTemplate(aePackageVO.getOperationName());
        		wupinShiyong.setShiyongTime(date);
        		wupinShiyong.setShoushuBianhao(aePackageVO.getOperationApplyid());
        		wupinShiyong.setRecordTime(date);
        		shiyongs.add(wupinShiyong);
        		packageImformation.setPackageTiaoma(aePackageVO.getWupinbaoTiaoma());
        		packageImformation.setShiyongLiushui(sdf.format(date)+seqVal[i]);
        		packageImformation.setShiyongkeshi("15");
        		packageImformation.setPatientId(aePackageVO.getPatientId());
        		packageImformation.setPatientHospitalNo(aePackageVO.getHosId());
        		packageImformation.setShoushuTemplate(aePackageVO.getOperationName());
        		packageImformation.setShiyongTime(date);
        		imformations.add(packageImformation);
        		i++;
    		}
        	if (!shiyongs.isEmpty()) {
        		wupinshiyongService.insertBatch(shiyongs);
    		}
        	if (!imformations.isEmpty()) {
        		imformationService.updateByBatch(imformations);
    		}
        	rtnMap.put("status", "true");
			rtnMap.put("msg", "保存成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "保存失败");
			e.printStackTrace();
		}

		return rtnMap;
	}
}

